const express = require('express')
const router = express.Router()
const User = require('../db/model/userModel')
const md5 = require('md5')

var param = {
    meta: {
        code: 200,
        msg: ''
    },
    data: ''
}

/**
 * @api {post} /user/login 用户登录
 * @apiName login
 * @apiGroup User
 *
 * @apiParam {String} phone 手机号(required)
 * @apiParam {String} password 密码(required)
 *
 * @apiSuccess {Object} meta 状态信息 
 * @apiSuccess {Object} data { gender,_id,phone,name,password,age,__v }
 * 
 * @apiError 401 登录失败，缺少参数
 * @apiError 402 登录失败，用户名或密码不正确
 */
router.post('/login', async (req, res) => {
    const { phone, password } = req.body
    if(!phone || !password) {
        param.meta.msg = '登录失败，缺少参数'
        param.meta.code = 401
        return res.send(param)
    }
    const result = await User.findOne({ phone, password: md5(password) })
    if(!result) {
        param.meta.msg = '登录失败，用户名或密码不正确'
        param.meta.code = 402
        return res.send(param)
    }
    param.meta.msg = '登录成功'
    param.data = result
    res.send(param)
})

/**
 * @api {post} /user/register 用户注册
 * @apiName register
 * @apiGroup User
 *
 * @apiParam {Number} phone 手机号(required)
 * @apiParam {String} name 用户名(required)
 * @apiParam {Number} password 密码(required)
 * @apiParam {Number} gender 性别(default 1)
 * @apiParam {Number} age 年龄
 * @apiParam {String} bio 简介
 *
 * @apiSuccess {Object} meta 状态信息 
 * @apiSuccess {Object} data 空
 * 
 * @apiError 401 注册失败，缺少参数
 */
router.post('/register', (req, res) => {
    const { phone, name, password, gender, age , bio } = req.body
    if(!phone||!name||!password) {
        param.meta.msg = '注册失败，缺少参数'
        param.meta.code = 401
        return res.send(param)
    }
    User.insertMany({ phone, name, password: md5(password), age, gender, bio })
    param.meta.msg = '注册成功'
    res.send(param)
})

module.exports = router